﻿using DrawTools.Tools;
using DrawTools.Utils;
using LS.DicomViewer.ViewModels;
using Microsoft.Win32;
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace LS.DicomViewer
{
    public partial class DicomViewer
    {
        private void DicomViewer_Unloaded(object sender, RoutedEventArgs e)
        {
            if (p3d != null)
            {
                try
                {
                    p3d.CloseMainWindow();
                    p3d.Close();
                }
                catch (Exception)
                {
                }
            }
        }
        DrawToolType drawToolType = DrawToolType.Length;

        private void ViewModel_PropertyChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            try
            {
                if (e.PropertyName == nameof(DicomViewModel.IsBusy))
                {
                    IsBusyChanged?.Invoke(ViewModel.IsBusy);
                }
                if (e.PropertyName == nameof(DicomViewModel.Playing))
                {
                    toolBar.IsEnabled = !ViewModel.Playing;
                }
                if (e.PropertyName == nameof(DicomViewModel.PixelRate))
                {
                    Dpi.PixelRate = ViewModel.PixelRate;
                }
                if (e.PropertyName == nameof(DicomViewModel.DicomFilePath))
                {
                    drawCanvas.DrawingToolType = drawToolType;
                    var drawTool = toolbar.Items.OfType<RadioButton>().FirstOrDefault(p => p.Tag.ToString() == drawCanvas.DrawingToolType.ToString());
                    if (drawTool != null) drawTool.IsChecked = true;
                }
                if (e.PropertyName == nameof(DicomViewModel.ShowDrawPoints))
                {
                    CurrentFrameIndexChanged(ViewModel.CurrentFrameIndex);
                }
            }
            catch { }
        }

        public Action<int?> CurrentFrameIndexChangedAction { get; set; }

        private void CurrentFrameIndexChanged(int? index)
        {
            if (ViewModel.CurrentDicom == null) return;
            try
            {
                Dispatcher.Invoke(() =>
                {
                    if (index == null || string.IsNullOrEmpty(ViewModel.DicomFilePath) || index < 0) return;

                    ClearDrawLines();
                    if (index.Value >= 0 && drawDataCache.ContainsKey(index.Value))
                    {
                        var drawData = drawDataCache[index.Value];
                        try
                        {
                            this.SetDrawData(drawData);
                        }
                        catch { }
                    }
                    else
                    {
                        var path = Path.Combine(ViewModel.CurrentDicom.ImageFilesDir, String.Format("{0}.xml", index));
                        if (File.Exists(path))
                        {
                            var xmlData = File.ReadAllText(path).TrimStart();
                            SetDrawData(xmlData);
                            drawDataCache.Add(index.Value, xmlData);
                        }
                    }
                    var drawTool = toolbar.Items.OfType<RadioButton>().FirstOrDefault(p => p.Tag.ToString() == drawCanvas.DrawingToolType.ToString());
                    if (drawTool != null) drawTool.IsChecked = true;
                    //this.drawCanvas.DrawingToolType = drawToolType;
                    drawToolType = drawCanvas.DrawingToolType;
                    CurrentFrameIndexChangedAction?.Invoke(index);
                });
            }
            catch (Exception) { }
        }

        private void CurrentFrameIndexChanging(int? index)
        {
            if (index == null) return;
            if (Dispatcher.HasShutdownStarted) return;
            Dispatcher.Invoke(() =>
            {
                if (this.drawCanvas.GetDrawGeometries().Count() > 0 && index >= 0)
                {
                    var drawData = this.GetCurrentFrameDrawData();
                    if (!string.IsNullOrEmpty(drawData))
                    {
                        if (drawDataCache.ContainsKey(index.Value))
                        {
                            drawDataCache[index.Value] = drawData;
                        }
                        else
                        {
                            drawDataCache.Add(index.Value, drawData);
                        }
                    }
                }
            });
        }

        private void OnDrawToolChecked(Object sender, RoutedEventArgs e)
        {
            if (e.Source is RadioButton btn && btn.Tag is String typeStr)
            {
                drawCanvas.DrawingToolType = (DrawToolType)Enum.Parse(typeof(DrawToolType), typeStr);
            }
        }

        private void btn_clear_Click(object sender, RoutedEventArgs e)
        {
            drawCanvas.Clear();
            toolbar.FindChildren<RadioButton>()?.ForEach(a => a.IsChecked = false);
        }

        private void OnSaveClick(Object sender, RoutedEventArgs e)
        {
        }

        private void OpenClick(Object sender, RoutedEventArgs e)
        {
            var folder = DrawFolder;
            var dlg = new OpenFileDialog
            {
                Filter = "XML文件(*.xml)|*.xml",
                DefaultExt = "xml",
                InitialDirectory = folder,
                RestoreDirectory = true
            };

            if (dlg.ShowDialog() == true)
            {
                this.drawCanvas.LoadDrawDataFromFile(dlg.FileName);
                drawDataCache.Clear();
            }
        }

        private void OnSaveImageClick(Object sender, RoutedEventArgs e)
        {
            var backgroundImage = this.drawViewer.BackgroundImage;

            var frame = this.drawCanvas.ToBitmapFrame(backgroundImage.PixelWidth, backgroundImage.PixelHeight, backgroundImage);

            if (frame == null) return;

            var folder = Path.Combine(Environment.CurrentDirectory, "Images");

            if (!Directory.Exists(folder))
                Directory.CreateDirectory("Images");

            var dlg = new SaveFileDialog
            {
                Filter = "图片文件(*.jpg;*.jpeg;*.png;*.bmp)|*.jpg;*.jpeg;*.png;*.bmp",
                OverwritePrompt = true,
                DefaultExt = "jpg",
                InitialDirectory = folder,
                RestoreDirectory = true
            };

            if (dlg.ShowDialog() == true)
                ImageHelper.Save(dlg.FileName, frame);
        }

        private void drawViewer_MouseWheel(object sender, MouseWheelEventArgs e)
        {
            ViewModel.Playing = false;
            ViewModel.NextCommand.Execute(e.Delta < 0 ? 1 : -1);
            e.Handled = true;
        }

        private void drawViewer_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Down || e.Key == Key.Right)
            {
                ViewModel.Playing = false;
                ViewModel.NextCommand.Execute(1);
                e.Handled = true;
            }
            else if (e.Key == Key.Up || e.Key == Key.Left)
            {
                ViewModel.Playing = false;
                ViewModel.NextCommand.Execute(-1);
                e.Handled = true;
            }
            else if (e.KeyboardDevice.Modifiers == ModifierKeys.Control)
            {
                if (e.Key == Key.A)
                {
                    ViewModel.Playing = false;
                    ViewModel.NextCommand.Execute(-1);
                    e.Handled = true;
                }
                else if (e.Key == Key.D)
                {
                    ViewModel.Playing = false;
                    ViewModel.NextCommand.Execute(1);
                    e.Handled = true;
                }
            }
            else if (e.Key == Key.F1)
            {
                if (ViewerConfigView.ShowConfigWindow != null)
                {
                    ViewerConfigView.ShowConfigWindow(new ViewerConfigView());
                }
                else
                {
                    var _ = DrawTools.DrawerConfig.Instance;
                    var w = new ConfigWindow();
                    w.Owner = Application.Current.MainWindow;
                    w.WindowStartupLocation = WindowStartupLocation.CenterOwner;
                    w.ShowDialog();
                }
            }
            //if (Keyboard.Modifiers.HasFlag(ModifierKeys.Control) && e.Key == Key.D1)
            //{
            //    drawCanvas.ToNextColor();
            //}
        }

        private void btn3D_Click(object sender, RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(LeftImagePath) && string.IsNullOrEmpty(RightImagePath))
            {
                HandyControl.Controls.MessageBox.Show("没有可加载的文件！");
                return;
            }
            try
            {
                try
                {
                    if (p3d != null)
                    {
                        p3d.CloseMainWindow();
                        p3d.Close();
                        p3d.Kill();
                    }
                }
                catch { }

                Task.Run(() =>
                {
                    var dir = Directory.GetParent(Dicom3DViewerPath).FullName;

                    var startInfo = new ProcessStartInfo();
                    startInfo.FileName = Path.GetFullPath(Dicom3DViewerPath);
                    startInfo.WorkingDirectory = dir;
                    startInfo.ArgumentList.Add(LeftImagePath ?? dir + @"\left1.dcm");
                    startInfo.ArgumentList.Add(RightImagePath ?? dir + @"\right1.dcm");
                    startInfo.ErrorDialog = true;

                    p3d = new Process();
                    try
                    {
                        var existPress = Process.GetProcessesByName(p3d.ProcessName);
                        if (existPress != null && existPress.Count() > 0)
                        {
                            existPress.ToList().ForEach(a => a.Kill());
                        }
                    }
                    catch { }

                    p3d.ErrorDataReceived += (s, e) =>
                    {
                        HandyControl.Controls.MessageBox.Show(e.Data);
                    };
                    p3d.StartInfo = startInfo;
                    p3d.Start();

                    p3d.WaitForExit();
                    var filesPath = Path.Combine(dir, "CutImages");
                    var files = Directory.GetFiles(filesPath);
                    if (files.Length > 0) View3DCutImagesAction?.Invoke(files);
                }).Await();
            }
            catch (Exception) { }
        }

    }
}